import { useEffect, useRef, RefObject } from 'react'
import { Modal, Form, Select, DatePicker, Input, message, FormInstance } from 'antd';
import moment, { Moment } from 'moment'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import { getDefaultDate, finishRequest } from './ajax'
import { awaitWrap } from '@js/tool'
import { ServiceTopicSchema } from '@src/components/schema/service';
const { confirm } = Modal
const { TextArea } = Input
const { Item } = Form
const { Option } = Select

const statusList = ['视为送达', '送达']

// 初始化默认送达主题完成时间
async function initDefaultSendedDate (theme: ServiceTopicSchema, formRef: RefObject<FormInstance>) {
  const hide = message.loading('加载中', 120)
  const [e, d] = await awaitWrap(getDefaultDate(theme.key))
  hide()
  if (e) {
    return message.error(e.message)
  }
  if (d) {
    formRef.current?.setFieldsValue({ complete_datetime: d })
  }
}

// 送达主题完成二次确认
function finishConfirm (d: {[k: string]: any}, theme: ServiceTopicSchema, hide: () => void, callback: () => void) {
  confirm({
    icon: <ExclamationCircleOutlined />,
    content: `请确认送达信息，送达情况：【${d.complete_type}】，送达时间为【${d.complete_datetime.format('YYYY年MM月DD日')}】，确认后信息无法修改。`,
    onOk: () => {
      finishRequestHandle(d, theme, hide, callback)
    }
  })
}

// 送达主题完成请求
async function finishRequestHandle (d: {[k: string]: any}, theme: ServiceTopicSchema, hide: () => void, callback: () => void) {
  const h = message.loading('提交中', 120)
  d.complete_datetime = Math.floor(d.complete_datetime / 1000)
  const [e] = await awaitWrap(finishRequest(d, theme))
  h()
  if (e) {
    return message.error(e.message)
  }
  hide()
  callback()
}

// 获取禁用时间
function banMinDate (current: Moment) {
  const minDate = moment(moment().format('YYYY-MM-DD'))
  const m = moment(minDate.format('YYYY-MM-DD'))
  const c = moment(current.format('YYYY-MM-DD'))
  return c > m
}

interface Props {
  visible: boolean
  topic: ServiceTopicSchema
  hide: () => void
  onFinish: () => void
}

function Main ({ visible, topic, hide = () => {}, onFinish = () => {} }: Props) {
  const formRef = useRef<FormInstance>(null)
  useEffect(() => {
    if (visible && topic) {
      initDefaultSendedDate(topic, formRef)
    }
  }, [visible, topic])
  return (
    <Modal
      title='整体送达情况'
      visible={visible}
      width={600}
      onOk={() => formRef.current?.submit()}
      onCancel={hide}
      maskClosable={false}
      destroyOnClose
    >
      <Form ref={formRef} labelCol={{ span: 4 }} onFinish={d => finishConfirm(d, topic, hide, onFinish)}>
        <Item name='complete_type' label='送达情况' rules={[{ required: true, message: '请选择送达情况' }]}>
          <Select placeholder='请选择送达情况'>
            {statusList.map(li => <Option key={li} value={li}>{li}</Option>)}
          </Select>
        </Item>
        <Item name='complete_datetime' label='送达时间' rules={[{ required: true, message: '请选择送达时间' }]}>
          <DatePicker disabledDate={c => banMinDate(c)} placeholder='送达时间不能为空' style={{ width: '100%' }} />
        </Item>
        <Item name='complete_info' label='备注'>
          <TextArea rows={3} />
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
